<?php

declare (strict_types=1);

namespace app\api\controller\shop;

use app\api\model\store\Shop;
use think\response\Json;
use cores\exception\BaseException;
use app\api\controller\Controller;
use app\api\model\Setting as SettingModel;
use app\api\model\store\shop\Order as ShopOrderModel;

/**
 * 自提订单管理
 * Class Order
 * @package app\api\controller\shop
 */
class Order extends Controller
{
    /**
     * 订单详情信息
     * @param int $orderId 订单ID
     * @return Json
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function detail(int $orderId): Json
    {
        // 订单详情
        $order = ShopOrderModel::getUserOrderDetail($orderId);
        return $this->renderSuccess([
            'order' => $order,  // 订单详情
            'setting' => [
                // 积分名称
                'points_name' => SettingModel::getPointsName(),
            ],
        ]);
    }

    /**
     * 确认核销 [已取货]
     * @param int $orderId 订单ID
     * @return Json
     * @throws BaseException
     */
    public function extract(int $orderId): Json
    {
        // 确认核销
        $model = new ShopOrderModel;
        if ($model->extract($orderId)) {
            return $this->renderSuccess([], '订单核销成功');
        }
        return $this->renderError($model->getError() ?: '核销失败');
    }

    public function pay(): Json
    {
        $model = new ShopOrderModel;
        $shopOrderId = $model->pay($this->postForm());
        if($shopOrderId){
            return $this->renderSuccess(['orderId'=>$shopOrderId], '订单核销成功');
        }else{
            return $this->renderError($model->getError() ?: '核销失败');
        }
    }

    public function shopOrderDetail(int $orderId): Json
    {
        $model = new ShopOrderModel();
        $orderDetail = $model->get($orderId);
        $shopModel = new Shop();
        $shopDetail = $shopModel->get($orderDetail->shop_id);
        return $this->renderSuccess(['order'=>$orderDetail,'shop'=>$shopDetail], '查询成功');
    }
}